Imports System.Runtime.InteropServices
Imports System.Diagnostics
Imports ActiveRecorder.User32Wrappers




Public Class frmMain
    Dim dtStart As DateTime
    Dim dtComStart As DateTime = DateTime.Now
    Dim bStart As Boolean = False
    Dim bIdle As Boolean = False
    Dim dir As String = System.AppDomain.CurrentDomain.BaseDirectory()
    Dim playTime As Long = 0
    Dim workTime As Long = 0
    Dim undefinedTime As Long = 0
    Dim idleTime As Long = 0
    Dim bWorking As Boolean = True
    Dim bWindowNameSelected As Boolean = True
    Public bOnTop As Boolean = False
    Public _InitialStyle As Integer

    Class Activity
        Public play As Boolean
        Public window As Boolean
        Public name As String
    End Class

    Dim Activities = New List(Of Activity)


    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim dtGapHour As Long = DateDiff(DateInterval.Hour, dtComStart, DateTime.Now)
        Dim dtGapMin As Long = DateDiff(DateInterval.Minute, dtComStart, DateTime.Now)
        Dim dtGapSec As Long = DateDiff(DateInterval.Second, dtComStart, DateTime.Now)
        lbComUsed.Text = dtGapHour.ToString("D2") & " : " & _
                        (dtGapMin Mod 60).ToString("D2") & " : " & _
                        (dtGapSec Mod 60).ToString("D2")



        lbTime.Text = DateTime.Now.Hour().ToString("D2") & " : " _
                    & DateTime.Now.Minute().ToString("D2") & " : " _
                    & DateTime.Now.Second().ToString("D2")

        If bIdle Then
            idleTime += 1
            lbIdled.Text = SecToTimeString(idleTime)
        ElseIf lbWorking.ForeColor = Color.Navy Then
            workTime += 1
            lbWorked.Text = SecToTimeString(workTime)

        ElseIf lbPlaying.ForeColor = Color.Red Then
            playTime += 1
            lbPlayed.Text = SecToTimeString(playTime)
        Else
            undefinedTime += 1
            lbUndefined.Text = SecToTimeString(undefinedTime)

        End If


        CheckForegroundwindow()

        CheckIdle()

    End Sub

    Private Sub CheckIdle()
        Dim lastInput As New LASTINPUTINFO
        Dim idleTime As Long

        lastInput.cbSize = Marshal.SizeOf(lastInput)

        If GetLastInputInfo(lastInput) Then

            idleTime = (Environment.TickCount - lastInput.dwTime) / 1000

        End If

        If (idleTime > 360) Then
            bIdle = True
            SetColorOfLabel(lbAway)
        Else
            bIdle = False
        End If
    End Sub

    Private Function SecToTimeString(ByVal sec As Long) As String
        Return (sec \ 3600).ToString("D2") & " : " & _
                            (sec \ 60 Mod 60).ToString("D2") & " : " & _
                            (sec Mod 60).ToString("D2")
    End Function

    Private Sub CheckForegroundwindow()
        Dim Length As Integer = 100
        Dim CurHwnd As Integer = GetForegroundWindow()


        Dim b As New System.Text.StringBuilder(ChrW(0), 100)
        Dim c As New System.Text.StringBuilder(ChrW(0), 500)

        Dim ret = GetWindowText(CurHwnd, b, b.Capacity)

        Dim idProc As Long = 0
        ret = GetWindowThreadProcessId(CurHwnd, idProc)

        'ret = GetWindowText(AnsHwnd, c, c.Capacity)

        'ret = GetWindowModuleFileName(CurHwnd, c, c.Capacity)

        If lstWindowName.Items.Count() = 0 OrElse b.ToString <> lstWindowName.Items.Item(0) Then
            lstWindowName.Items.Insert(0, b.ToString)

            If lstWindowName.Items.Count > 500 Then
                lstWindowName.Items.RemoveAt(499)
            End If


            'check file name
            Dim procname As String = c.ToString

            Dim arrProcesses As Process() = Process.GetProcesses()

            For i As Integer = 0 To arrProcesses.Length - 1
                Dim objProcess1 As Process = arrProcesses(i)
                If Not (objProcess1.MainWindowHandle = IntPtr.Zero) Then
                    Dim objProcess As MyProcInfo = New MyProcInfo(objProcess1)
                    If Not (objProcess.ProcInfo.MainWindowHandle = IntPtr.Zero) Then
                        Dim hWnd As IntPtr = objProcess.ProcInfo.MainWindowHandle

                        If hWnd = CurHwnd Then
                            procname = objProcess.ProcInfo.ProcessName
                        End If
                    End If
                End If
            Next

            'filename = filename.Substring(filename.LastIndexOf("\") + 1)


            lstProcName.Items.Insert(0, procname)

            If lstProcName.Items.Count > 500 Then
                lstProcName.Items.RemoveAt(499)
            End If

            CheckActivity()
        End If

    End Sub

    Private Sub CheckActivity()
        If bIdle Then
            Return
        End If
        Dim windowName As String = lstWindowName.Items.Item(0)
        Dim procName As String = lstProcName.Items.Item(0)
        Dim itis As Boolean = False
        Dim play As Boolean = True

        'check window
        For Each act As Activity In Activities
            If Not act.window Then Continue For
            play = act.play


            If act.name.StartsWith("%") And act.name.EndsWith("%") Then
                itis = windowName.Contains(act.name.Substring(1, act.name.Length - 2))
            ElseIf act.name.StartsWith("%") Then
                itis = windowName.EndsWith(act.name.Substring(1))
            ElseIf act.name.EndsWith("%") Then
                itis = windowName.StartsWith(act.name.Substring(0, act.name.Length - 2))
            ElseIf windowName = act.name Then
                itis = True
            End If

            If itis Then
                Exit For
            End If

        Next

        'check proc
        If Not itis Then
            For Each act As Activity In Activities
                If act.window Then Continue For
                play = act.play
                If act.name = procName Then
                    itis = True
                    Exit For
                End If
            Next
        End If

        SetColorOfLabel(lbNothing)
        If itis Then
            If play Then
                SetColorOfLabel(lbPlaying)
            Else
                SetColorOfLabel(lbWorking)
            End If
        End If
    End Sub

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(dir + "\record.txt", True)
        file.WriteLine(dtStart & " ~ " & DateTime.Now & ", play=" & lbPlayed.Text & _
                                      ", work=" & lbWorked.Text & _
                                      ", away=" & lbIdled.Text & _
                                      ", undefined=" & lbUndefined.Text)
        file.Close()

    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If Not My.Computer.FileSystem.FileExists(dir + "\activities.txt") Then
            Dim file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(dir + "\activities.txt", True)
            file.Close()
        End If
        Dim strActs As String = My.Computer.FileSystem.ReadAllText(dir + "\activities.txt")
        Dim index As Integer


        While (True)
            index = strActs.IndexOf(vbNewLine)
            If index < 1 Then
                Exit While
            End If

            Dim act As Activity = New Activity
            act.play = strActs.StartsWith("play,")
            act.window = strActs.Substring(5).StartsWith("wind,")
            act.name = strActs.Substring(10, index - 10)
            Activities.Add(act)
            strActs = strActs.Substring(index + 2)
        End While


        dtStart = DateTime.Now
        _InitialStyle = GetWindowLong(Me.Handle, GWL.ExStyle)
    End Sub

    Private Sub lstWindowName_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstWindowName.Click
        txtFilter.Text = lstWindowName.SelectedItem.ToString
        lstWindowName.SelectedIndex = -1

        bWindowNameSelected = True
    End Sub

    Private Sub lstWindowName_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstWindowName.DoubleClick

    End Sub

    Private Sub lstProcName_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstProcName.Click
        txtFilter.Text = lstProcName.SelectedItem.ToString
        bWindowNameSelected = False
        lstProcName.SelectedIndex = -1
    End Sub



    Private Sub SetColorOfLabel(ByVal sender As Object)
        lbPlaying.ForeColor = Color.Silver
        lbWorking.ForeColor = Color.Silver
        lbNothing.ForeColor = Color.Silver
        lbAway.ForeColor = Color.Silver

        If (sender.Equals(lbPlaying)) Then
            lbPlaying.ForeColor = Color.Red
            Me.Text = "AR - Playing"
        ElseIf (sender.Equals(lbWorking)) Then
            lbWorking.ForeColor = Color.Navy
            Me.Text = "AR - Working"
        ElseIf (sender.Equals(lbNothing)) Then
            lbNothing.ForeColor = Color.Black
            Me.Text = "AR - Nothing"
        ElseIf (sender.Equals(lbAway)) Then
            lbAway.ForeColor = Color.GreenYellow
            Me.Text = "AR - Away"
        End If
    End Sub


    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddPlay.Click, btnStop.Click
        If txtFilter.Text = "" Then
            Return
        End If

        Dim type, type2 As String

        Dim act As New Activity()

        If sender.Equals(btnAddPlay) Then
            type = "play,"
            act.play = True
        Else
            type = "work,"
            act.play = False
        End If

        If bWindowNameSelected Then
            type2 = "wind,"
            act.window = True
        Else
            type2 = "proc,"
            act.window = False
        End If


        act.name = txtFilter.Text
        Activities.Add(act)

        Dim file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(dir + "\activities.txt", True)
        file.WriteLine(type & type2 & txtFilter.Text)
        file.Close()

        CheckActivity()

    End Sub



    Public Sub btOnTop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btOnTop.Click
        If Not bOnTop Then
            Me.Height = 255
            Me.Opacity = 0.7
            Me.TopMost = True
            btOnTop.Text = "Back to normal"
            SetWindowLong(Me.Handle, GWL.ExStyle, _
                _InitialStyle Or WS_EX.Layered Or WS_EX.Transparent)

            Dim pt As Point
            pt = Me.PointToScreen(btOnTop.Location)

            BackToNormal.Location = pt
            BackToNormal.ShowInTaskbar = False
            BackToNormal.Button1.Size = btOnTop.Size()
            BackToNormal.Size = btOnTop.Size()
            BackToNormal.ShowDialog()
        End If
        bOnTop = Not bOnTop
    End Sub

    Private Sub lstWindowName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstWindowName.SelectedIndexChanged

    End Sub
End Class